
const schedule = require('node-schedule');

class ScheduledJob {
    constructor(cron, fn) {
        this.cron = cron;
        this.fn = fn;
        this.id = this.generateId();
        this.job = undefined; // 保存实际的schedule Job
    }

    generateId() {
        return Date.now().toString(36); // 生成一个基于当前时间的唯一ID
    }

    start() {
        this.job = schedule.scheduleJob(this.cron, this.fn);
    }

    stop() {
        if (this.job) {
            this.job.cancel();
            this.job = undefined;
        }
    }

    // 序列化方法
    serialize() {
        return {
            cron: this.cron,
            fn: this.fn.toString(), // 如果fn是函数，需要转换为字符串
            id: this.id,
            paused: this.job ? this.job.paused : false,
            running: this.job ? this.job.running : false,
        };
    }

    // 反序列化方法
    static deserialize(data) {
        const job = new ScheduledJob(data.cron, new Function(data.fn)); // 注意这里需要重新创建函数
        job.id = data.id;
        job.paused = data.paused;
        job.running = data.running;

        return job;
    }
}

// 使用示例
const job = new ScheduledJob('*/5 * * * * *', () => console.log('定时任务执行中...'));
job.start();
job.stop() ;
// 序列化
const serializedJob = job.serialize();
console.log('Serialized job:', serializedJob);

// 反序列化
const deserializedJob = ScheduledJob.deserialize(serializedJob);
 deserializedJob.start(); // 如果需要，可以再次启动反序列化的任务

